package com.wuchaooooo.service.zjutsds.controller;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wuchaooooo.service.zjutsds.dao.QueryDAO;
import com.wuchaooooo.service.zjutsds.service.SmsService;

/**
 * Created by arthur on 01/19/2020.
 */
@Controller
@RequestMapping("query")
public class QueryController {
	@Autowired
	private QueryDAO queryDao;
	@Autowired
	private SmsService smsService;


	@GetMapping("/")
	public String rootPath(HttpServletRequest req) {
		// 登录检查
		HttpSession session = req.getSession(false);
		if (session == null || session.getAttribute("user") == null) {
			return "redirect:/query/login";
		}
		
		return "redirect:/query/gkSearch";
	}

	@GetMapping("/login")
	public String login() {

		return "query/login";
	}

	@PostMapping("/login")
	@ResponseBody
	public Map<String, String> login(@RequestParam Map<String, Object> params, HttpServletRequest req) {
		Map<String, String> result = new HashMap<String, String>();
		Map<String, Object> user = queryDao.loginUser(params);
		if(user == null) {
			result.put("status", "error");
			result.put("message", "用户登录失败，请重新输入用户名或密码。");
		} else {
			req.getSession().setAttribute("user", user);
			result.put("status", "success");
		}
		return result;
	}

	@GetMapping("/signup")
	public String signup() {

		return "query/signup";
	}

	@PostMapping("/signup")
	@ResponseBody
	public Map<String, String> signup(@RequestParam Map<String, Object> params) {
		Map<String, String> result = new HashMap<String, String>();
		if(queryDao.addUser(params) == 0) {
			result.put("status", "error");
			result.put("message", "注册用户失败，您可能已经注册过账号。");
		} else {
			result.put("status", "success");
		}
		return result;
	}

	@GetMapping("/checkcode")
	@ResponseBody
	// return json
	public Map<String, String> checkcode(@RequestParam String code, @RequestParam String phoneNo,HttpServletRequest req) {
		Map<String, String> result = new HashMap<String, String>();

		HttpSession session = req.getSession(false);
		if (session != null) {
			String sCode = session.getAttribute("code") != null ? String.valueOf(session
					.getAttribute("code")) : null;
			String sPhoneNo = session.getAttribute("phoneNo") != null ? String.valueOf(session
					.getAttribute("phoneNo")) : null;
			String sTime = session.getAttribute("time") != null ? String.valueOf(session
					.getAttribute("time")) : null;

			if (sCode == null) {
				result.put("status", "error");
				result.put("message", "请您先获取验证码。");
				return result;
			}
			
			if ((Calendar.getInstance().getTimeInMillis() - Long.valueOf(sTime)) / 1000 > 600) {
				result.put("status", "error");
				result.put("message", "您的验证码已过期，请重新获取验证码。");
				return result;
			}
			
			if (!phoneNo.equals(sPhoneNo)) {
				result.put("status", "error");
				result.put("message", "您输入的手机号码与获取验证码的手机号码不一致，请重新输入。");
				return result;
			}
			
			if (!sCode.equals(code)) {
				result.put("status", "error");
				result.put("message", "您的验证码不正确，请重新输入验证码。");
				return result;
			}
		}
		result.put("status", "success");
		return result;
	}

	@GetMapping("/getcode")
	@ResponseBody
	// return json
	public Map<String, String> getcode(@RequestParam String phoneNo, HttpServletRequest req) {
		Map<String, String> result = new HashMap<String, String>();
		// 生成验证码
		String code = StringUtils.leftPad(RandomStringUtils.randomNumeric(4), 4, "0");
		String json = "{\"code\":\"" + code + "\"}";
		String resultCode = smsService.sendAndReceiveSms(phoneNo, "辽宁金榜无忧", "SMS_151765024", json);
		if (!"OK".equals(resultCode)) {
			result.put("status", "error");
			result.put("message", "发送验证码时错误，请您稍后再试。");
		} else {
			req.getSession().setAttribute("code", code);
			req.getSession().setAttribute("phoneNo", phoneNo);
			req.getSession().setAttribute("time", Calendar.getInstance().getTimeInMillis());
			result.put("status", "success");
			result.put("message", "验证码已发送至您的手机。");
		}
		return result;
	}

	@GetMapping("/gkSearch")
	public String gkQuery(HttpServletRequest req) {
		// 登录检查
		HttpSession session = req.getSession(false);
		if (session == null || session.getAttribute("user") == null) {
			return "redirect:/query/login";
		}
		
		return "query/gkSearch";
	}
	
	@PostMapping("/selScore")
	// @ResponseBody // return json
	public String getSelScore(@RequestParam Map<String, Object> params, Map<String, Object> model, HttpServletRequest req) {

		HttpSession session = req.getSession(false);
		if (session == null || session.getAttribute("user") == null) {
			return "redirect:/query/login";
		}

		List<Map<String, Object>> list = queryDao.getQuery(params);
		Map<String, List<Map<String, Object>>> map = list.stream().collect(
				Collectors.groupingBy(item -> String.valueOf(item.get("name")) + "<"
						+ String.valueOf(item.get("province")) + "-"
						+ String.valueOf(item.get("city")) + ">" + String.valueOf(item.get("level")) ));
		model.put("map", map);
		return "query/result";
	}

	// 练习用
	// @GetMapping("/major")
	// @ResponseBody
	// public List<Map<String, Object>> getMajor() {
	// return QueryDao.getMajors();
	//
	// }
}
